<template>
  <el-dialog :title="model.id?'编辑用户':'添加用户'" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="modelRules" :model="model" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="model.username" placeholder="用户名" />
      </el-form-item>
      <el-form-item v-if="!model.id" label="密码" prop="password">
        <el-tooltip v-model="capsTooltip" content="大写锁定已开启" placement="top" manual>
          <el-input :key="isPasswordType" v-model="model.password" :type="isPasswordType?'password':''" placeholder="新密码" @keyup.native="checkCapslock" @blur="capsTooltip = false">
            <template slot="append">
              <span class="show-pwd" @click="isPasswordType = !isPasswordType">
                <svg-icon :icon-class="isPasswordType ? 'eye' : 'eye-open'" />
              </span>
            </template>
          </el-input>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="model.nickname" placeholder="昵称" />
      </el-form-item>
      <el-form-item label="邮箱地址" prop="email">
        <el-input v-model="model.email" placeholder="邮箱地址" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone_number">
        <el-input v-model="model.phone_number" placeholder="手机号码" />
      </el-form-item>

      <el-form-item label="选择角色" prop="group_ids">
        <el-checkbox-group v-model="model.group_ids">
          <el-checkbox v-for="(item, index) in groupList" :key="index" :label="item.id">{{ item.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item prop="lockout_enabled">
        <el-checkbox v-model="model.lockout_enabled">登录尝试失败后锁定帐户</el-checkbox>
      </el-form-item>
      <el-form-item prop="is_active">
        <el-checkbox v-model="model.is_active">启用</el-checkbox>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" :loading="isSubmitLoading" @click="save()">提交</el-button>
    </div>
  </el-dialog>
</template>
<script>
import abp from 'abp'
import { getUser, createUser, updateUser, getGroupList } from "@/api/identity/user";

export default {
  data() {
    // const validatePassword = (rule, value, callback) => {
    //   const givenPassword = value;
    //   if (!givenPassword || givenPassword.length < 0) {
    //     callback(new Error(`请输入密码`));
    //   }

    //   const requiredLength = this.passwordComplexitySetting.requiredLength;
    //   if (requiredLength && givenPassword && givenPassword.length < requiredLength) {
    //     callback(new Error(`密码至少需要${requiredLength}个字符`));
    //   }

    //   const requireDigit = this.passwordComplexitySetting.requireDigit;
    //   if (requireDigit && givenPassword && !/[0-9]/.test(givenPassword)) {
    //     callback(new Error(`密码必须包含数字`));
    //   }

    //   const requireUppercase = this.passwordComplexitySetting.requireUppercase;
    //   if (requireUppercase && givenPassword && !/[A-Z]/.test(givenPassword)) {
    //     callback(new Error(`密码必须包含大写字母`));
    //   }

    //   const requireLowercase = this.passwordComplexitySetting.requireLowercase;
    //   if (requireLowercase && givenPassword && !/[a-z]/.test(givenPassword)) {
    //     callback(new Error(`密码必须包含小写字母`));
    //   }

    //   const requireNonAlphanumeric = this.passwordComplexitySetting.requireNonAlphanumeric;
    //   if (requireNonAlphanumeric && givenPassword && /^[0-9a-zA-Z]+$/.test(givenPassword)) {
    //     callback(new Error(`密码必须包含标点符号`));
    //   }

    //   callback();
    // };

    return {
      passwordComplexitySetting: {
        requiredLength: abp.setting.getInt('Abp.Identity.Password.RequiredLength'),
        requireDigit: abp.setting.getBoolean('Abp.Identity.Password.RequireDigit'),
        requireUppercase: abp.setting.getBoolean('Abp.Identity.Password.RequireUppercase'),
        requireLowercase: abp.setting.getBoolean('Abp.Identity.Password.RequireLowercase'),
        requireNonAlphanumeric: abp.setting.getBoolean('Abp.Identity.Password.RequireNonAlphanumeric'),
        requiredUniqueChars: abp.setting.getInt('Abp.Identity.Password.RequiredUniqueChars')
      },
      isPasswordType: true,
      capsTooltip: false,

      dialogVisible: false,
      isSubmitLoading: false,
      id: undefined,
      model: {
        username: "",
        nickname: "",
        password: "",
        email: "",
        phone_number: "",
        lockout_enabled: true,
        is_active: true,
        register_type: 'admin',
        group_ids: []
      },
      modelRules: {
        username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
        nickname: [{ required: true, trigger: "blur", message: "请输入昵称" }],
        // password: [{ required: true, trigger: "blur", validator: validatePassword }],
        email: [{ type: "email", required: true, trigger: "blur", message: "请输入邮箱地址" }],
        phone_number: [{ required: true, trigger: "blur", message: "请输入手机号码" }]
      },

      groupList: []
    };
  },
  created() {
    this.getGroupList()
  },
  methods: {
    getGroupList() {
      getGroupList().then(result => {
        this.groupList = result.items
      })
    },
    show(id) {
      this.id = id;
      this.resetModal();
      this.isSubmitLoading = false;
      if (this.id) {
        getUser(this.id).then(result => {
          this.model = result;
          const groups = result.groups.map(item => {
            return item.id
          })
          this.$set(this.model, "group_ids", groups)
          this.dialogVisible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].clearValidate();
          });
        });
      } else {
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      }
    },
    resetModal() {
      this.model = {
        username: "",
        password: "",
        nickname: "",
        email: "",
        phone_number: "",
        lockout_enabled: true,
        is_active: true,
        register_type: 'admin',
        group_ids: []
      };
    },
    save() {
      this.isSubmitLoading = true;
      this.$refs["dataForm"].validate(valid => {
        if (!valid) {
          this.isSubmitLoading = false;
          this.$message({ message: this.$t("formIsNotValidMessage"), type: "warning" });
          return;
        }

        let obj;
        if (this.id) {
          const { username, nickname, email, phone_number, lockout_enabled, is_active, group_ids } = this.model;
          const data = { username, nickname, email, phone_number, lockout_enabled, is_active, group_ids }
          obj = updateUser(this.id, data);
        } else {
          const { username, nickname, password, email, phone_number, lockout_enabled, is_active, register_type, group_ids } = this.model;
          const data = { username, nickname, password, email, phone_number, lockout_enabled, is_active, register_type, group_ids }

          obj = createUser(data);
        }

        obj.then((result) => {
          this.$message({ message: this.id ? "编辑成功" : "添加成功", type: "success" });
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
          this.close();
          this.$emit("save");
        }).finally(() => {
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
        })
      });
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if ((shiftKey && (key >= "a" && key <= "z")) || (!shiftKey && (key >= "A" && key <= "Z"))) {
          this.capsTooltip = true;
        } else {
          this.capsTooltip = false;
        }
      }
      if (key === "CapsLock" && this.capsTooltip === true) {
        this.capsTooltip = false;
      }
    },
    close() {
      this.dialogVisible = false;
      this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
    }
  }
};
</script>
